﻿using Dapper;
using EWC.Core.DependencyInjection;
using EWC.HIS.Dapper.Data;
using EWC.HIS.Domain.Data.Uow;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EWC.HIS.Dapper.Data.Uow
{
    public class UnitOfWork : IUnitOfWork, IScopedDependency
    {
        private readonly DbContext _dbContext;
        private DbTransaction _transaction;

        public UnitOfWork(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        private bool _disposed;
        private enum TransactionStatus { None, Committed, RolledBack };
        private TransactionStatus _transactionStatus = TransactionStatus.None;

        public async ValueTask BeginTransactionAsync()
        {
            _transaction = await _dbContext.BeginTransactionAsync();
        }

        public async Task CommitAsync()
        {
            CheckDisposed();
            if (_transactionStatus == TransactionStatus.RolledBack)
            {
                throw new InvalidOperationException("事务已回滚，无法提交事务。");
            }
            if (_transactionStatus == TransactionStatus.Committed)
            {
                throw new InvalidOperationException("事务已提交，无法重复提交事务。");
            }
            await _transaction.CommitAsync();
            _transactionStatus = TransactionStatus.Committed;
        }

        public async Task RollbackAsync()
        {
            CheckDisposed();
            if (_transactionStatus == TransactionStatus.RolledBack)
            {
                throw new InvalidOperationException("事务已回滚，无法重复回滚事务。");
            }
            if (_transactionStatus == TransactionStatus.Committed)
            {
                throw new InvalidOperationException("事务已提交，不能回滚事务。");
            }
            await _transaction.RollbackAsync();
            _transactionStatus = TransactionStatus.RolledBack;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public async ValueTask DisposeAsync()
        {
            await DisposeAsyncCore();
            Dispose(false);
            GC.SuppressFinalize(this);
        }

        protected virtual async ValueTask DisposeAsyncCore()
        {
            if (!_disposed)
            {
                await _transaction.DisposeAsync();
            }
            _disposed = true;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // 释放托管资源（如果有）
                }
                _transaction.Dispose();
                _disposed = true;
            }
        }

        ~UnitOfWork()
        {
            Dispose(false);
        }

        private void CheckDisposed()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(UnitOfWork), "当前对象已被释放。");
            }
        }
    }
}
